05. Intro to Flask

Introduction to Flask

Flask is the tool we'll use to create our api server.

It is a "micro" framework, which means that its core functionality is kept simple, but that there are numerous extensions to allow developers to add other functionality (such as authentication and database support).

FSND C2 L2 A06 Introduction To Flask

In this section we will cover:

  • Creating a basic Flask application
  • Writing a basic endpoint
  • Checking the response using Curl.

Creating a basic Flask application

FSND C2 L2 A07 Flask Example Part 1

Intro to Flask Example Summary

Flask Set Up Summary

Starting any Flask app will follow the same general flow for a simple application. The steps below are the same steps as taken in the screencast and can be referenced if you get stuck during the exercise.

Directory & Virtualenv Set Up

  1. Create the project directory mkdir [project_name] and navigate into it
  2. Install flask using pip pip3 install flask
  3. Make the flaskr directory and flaskr/__init__.py file within it

At this point you're ready to start working on your app!

Create_app

In our setup, we will configure the basic Flask app. In these notes, I'll also include how to set up the application to handle specialized configuration.

Basic App

  1. Import your dependencies
    • from flask import Flask, jsonify
  2. Define the create_app function with parameter test_config initially set to None . Then within the function:
  3. Define the application. Ensure you include the first parameter. __name__ is the name of the current Python module.
    • app = Flask(__name__)
  4. Return the app instance.
    • return app

Configured Application

The below information is for your reference and related information can be found in the Flask documentation. You are expected to use the basic application set up for this course. However, as you build larger applications that utilize multiple environments and configurations (production, development, testing, etc) this knowledge will be helpful for streamlining your development process.

  1. Import additional dependencies. You'll need to import os in order to access the operating system and file structure
    import os

  2. Set up your default configuration. When working in development your SECRET_KEY can be hardcoded as shown but for production should come from a secret environment variable. DATABASE is the path for the database file.

 app.config.from_mapping(
    SECRET_KEY='dev',
    DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite')
    )
  1. If a config.py file is included in the instance folder, use its values to override the default configuration, for instance the SECRET_KEY . You can also enable a testing configuration if it was passed into the create_app function.
if test_config is None:
    # load the instance config, if it exists, when not testing
    app.config.from_pyfile('config.py', silent=True)
else:
    # load the test config if passed in
    app.config.from_mapping(test_config)
  1. Make the instance path directory. The app will create the database file within that directory so it needs to exist.
try:
    os.makedirs(app.instance_path)
except OSError:
    pass

First Endpoint with JSON

Before you return the app, use the @app.route decorator to create an endpoint to path / and define a function to handle that route.

@app.route('/')
def hello_world():
    return 'Hello, World!'

return app

Instead of returning text, use jsonify to send an object containing the message

 return jsonify({'message':'Hello, World!'})

Run your application

In the command line, you'll run three lines of code. The first two lines tell the terminal where to find your application and to run it in development mode, which allows you to keep it running while it hotloads any modifications. The third actually starts the application. If running your application on Windows

export FLASK_APP=flaskr
export FLASK_ENV=development
flask run

After you start the application you'll see output like will look like the following:

 * Serving Flask app "flaskr" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 192-247-084

Visit the provided URL and you should see {'message':'Hello, World!'} displayed. You can try adding more endpoints or changing the response before moving forward.

Practice Workspace

You can try the steps above locally on your own machine, or you can use the workspace below.

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter-lab
  • Opened files (when workspace is loaded): n/a

FSND C2 L2 A08 Flask Example Part 2

What method(s) does the following app.route decorator respond to?

@app.route('/messages')
def read():
    return jsonify({'messages': []})
SOLUTION:
  • GET